<?php
/**
 * Direct Model Table Verification Script
 * Reads Model files directly to check table property values
 */

echo "🧪 Testing Model Table Mappings by Direct File Analysis...\n\n";

// Model files to check
$modelFiles = [
    __DIR__ . '/app/common/model/Device.php' => 'gf_device',
    __DIR__ . '/app/common/model/ChannelStats.php' => 'gf_channel_stats',
    __DIR__ . '/app/common/model/AttributionEvent.php' => 'gf_attribution_event',
    __DIR__ . '/app/common/model/AttributionInstall.php' => 'gf_attribution_install',
    __DIR__ . '/app/common/model/AttributionTrack.php' => 'gf_attribution_track',
];

$successCount = 0;
$failedCount = 0;
$errors = [];

foreach ($modelFiles as $filePath => $expectedTable) {
    $modelName = basename($filePath, '.php');
    echo "Testing Model: $modelName\n";
    echo "Expected table: $expectedTable\n";
    
    if (!file_exists($filePath)) {
        echo "  ❌ Model file not found: $filePath\n";
        $failedCount++;
        $errors[] = "$modelName: File not found";
        continue;
    }
    
    try {
        $content = file_get_contents($filePath);
        
        // Look for protected $table = 'table_name'; (handle comments and whitespace)
        if (preg_match("/protected\s*\$table\s*=\s*['\"]([^'\"]+)['\"]/s", $content, $matches)) {
            $actualTable = $matches[1];
            echo "  Actual table: $actualTable\n";
            
            if ($actualTable === $expectedTable) {
                echo "  ✅ Table name matches expected value\n";
                $successCount++;
            } else {
                echo "  ❌ Table name mismatch: expected $expectedTable, got $actualTable\n";
                $failedCount++;
                $errors[] = "$modelName: Table name mismatch";
            }
        } else {
            echo "  ❌ No protected \$table property found in model\n";
            $failedCount++;
            $errors[] = "$modelName: No table property found";
        }
        
    } catch (Exception $e) {
        echo "  ❌ Error reading file: " . $e->getMessage() . "\n";
        $failedCount++;
        $errors[] = "$modelName: Error reading file - " . $e->getMessage();
    }
    
    echo "\n";
}

echo "📊 TEST RESULTS:\n";
echo "==================================================\n";
echo "Total models tested: " . count($modelFiles) . "\n";
echo "✅ Successful: $successCount\n";
echo "❌ Failed: $failedCount\n";
echo "Success rate: " . round(($successCount / count($modelFiles)) * 100, 2) . "%\n\n";

if ($failedCount > 0) {
    echo "❌ ERRORS ENCOUNTERED:\n";
    echo "==================================================\n";
    foreach ($errors as $error) {
        echo "- $error\n";
    }
    echo "\n";
}

if ($successCount === count($modelFiles)) {
    echo "🎉 ALL MODEL TABLE MAPPINGS ARE CORRECT!\n";
    echo "✅ All models use the expected gf_ prefixed table names.\n";
} else {
    echo "⚠️  Some issues were found. Please review the errors above.\n";
}

echo "\n🏁 Model table mapping test completed!\n";

// Additional verification - check if any models still need updating
echo "\n🔍 ADDITIONAL VERIFICATION:\n";
echo "==================================================\n";

// Check for any remaining models that might need updating
$allModelFiles = glob(__DIR__ . '/app/common/model/*.php');
$modelsNeedingUpdate = [];

foreach ($allModelFiles as $file) {
    $content = file_get_contents($file);
    if (preg_match("/protected\s+\$table\s*=\s*['\"]([^'\"]+)['\"]/", $content, $matches)) {
        $tableName = $matches[1];
        if (!str_starts_with($tableName, 'gf_')) {
            $modelsNeedingUpdate[] = [
                'model' => basename($file, '.php'),
                'table' => $tableName
            ];
        }
    }
}

if (count($modelsNeedingUpdate) > 0) {
    echo "⚠️  Models that still need gf_ prefix update:\n";
    foreach ($modelsNeedingUpdate as $model) {
        echo "  - {$model['model']}: uses table '{$model['table']}'\n";
    }
} else {
    echo "✅ All models use gf_ prefixed table names!\n";
}

echo "\n";

?>